// ==UserScript==
// @name         WPS-定时每日签到
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.1
// @description  WPS任务中心每日定时自动签到，周末可获得两日会员。
// @author       Free-wang 完成主要代码、逻辑思路、以及整体架构的开发
// @contributor  DeepSeek 提供部分代码、逻辑分析、以及语法设计的辅助
// @license      MIT
// @supportURL   https://scriptcat.org/zh-CN/script-show-page/3777/issue
// @website      https://gitee.com/ihacker/UserScripts/
// @source       https://gitee.com/ihacker/UserScripts/blob/master/crontab-user-script/WPS-%E5%AE%9A%E6%97%B6%E6%AF%8F%E6%97%A5%E7%AD%BE%E5%88%B0.js
// @icon         https://img.icons8.com/?id=6GHlhyEr8VcU
// @crontab      * 0-23 once * *
// @grant        GM_xmlhttpRequest
// @grant        GM_notification
// @grant        GM_cookie
// @grant        GM_info
// @grant        GM_log
// @connect      personal-act.wps.cn
// @require      https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
// ==/UserScript==

const TASK_CENTER_URL = "https://personal-act.wps.cn/rubik2/portal/HD2025031821201822/YM2025031821202008";

/**
 * 获取cookie
 * @returns {Promise}
 */
async function getCookies() {
    // 返回一个Promise对象
    return new Promise((resolve, reject) => {
        // 调用GM_cookie.list方法，传入url和回调函数
        GM_cookie.list({ url: TASK_CENTER_URL }, (cookies, error) => {
            // 如果有错误，则reject
            if (error) {
                reject(error);
            } else {
                // 否则resolve
                resolve(cookies);
            }
        });
    });
}

/**
 * 获取任务中心页面状态
 * @returns {Promise}
 * <p>isNotLogged: 是否未登录</p>
 * <p>isSigned: 是否已签到</p>
 */
async function getPageStatus() {
    // 获取cookie
    const cookies = await getCookies();
    // 获取页面状态
    return new Promise((resolve, reject) => {
        // 获取今日签到信息
        GM_xmlhttpRequest({
            method: "GET",
            url: TASK_CENTER_URL,
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
                "Accept": "application/json, text/plain, */*",
                "Accept-Language": "zh-CN,zh;q=0.9",
                "Cookie": cookies.map(c => `${c.name}=${c.value}`).join('; '),
                "Referrer": "https://personal-act.wps.cn/rubik2/portal/HD2025031821201822/YM2025031821202008"
            },
            onload: function (response) {
                try {
                    const parser = new DOMParser();
                    const document = parser.parseFromString(response.responseText, "text/html");
                    // 1. 登录状态检测
                    const loginButton = document.querySelector('button.username');
                    const isNotLogged = loginButton?.textContent.includes('请登录');
                    // 2. 签到状态检测(双重验证)
                    const signButton = document.querySelector('[class*="sign-opera-btn"]');
                    const signButtonText = signButton.textContent || signButton.innerText;
                    const isSigned = signButton?.getAttribute('disabled') === 'true' && signButtonText.includes('已签到');
                    // 3. 返回结果
                    GM_log(`${GM_info.script.name}脚本日志：isNotLogged=${isNotLogged}、isSigned=${isSigned}`, "info");
                    resolve({
                        isNotLogged, isSigned
                    });
                } catch (error) {
                    GM_log(`${GM_info.script.name}脚本日志：${error.toString()}`, "error");
                    reject(`任务中心页面DOM解析错误：${error.toString()}`);
                }
            },
            onerror: (error) => reject(`任务中心页面请求失败：${error.toString()}`)
        });
    });
}

/**
 * 执行签到请求
 * @param actId 入参
 * @returns {Promise}
 */
async function performSignIn(actId) {
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: "POST",
            url: "https://vip.wps.cn/sign/v2",
            headers: {
                "Content-Type": "application/json",
                "Referer": TASK_CENTER_URL
            },
            data: JSON.stringify({actId}),
            onload: resolve,
            onerror: (error) => reject(`执行签到失败：${error.toString()}`)
        });
    });
}

return new Promise((resolve, reject) => {
    const asyncFunction = async () => {
        try {
            const {isNotLogged, isSigned} = await getPageStatus();
            if (isNotLogged) {
                GM_notification({
                    title: `《${GM_info.script.name}》脚本提示`,
                    text: "WPS任务中心未登录，请先登录帐号！"
                });
                return;
            }
            if (isSigned) {
                GM_notification({
                    title: `《${GM_info.script.name}》脚本提示`,
                    text: "WPS任务中心已签到，无需重复签到！",
                });
                return;
            }

            await performSignIn("actId");
            const {isSigned: checkSigned} = await getPageStatus();
            if (checkSigned) {
                GM_notification({
                    title: `《${GM_info.script.name}》脚本提示`,
                    text: "WPS任务中心签到成功"
                });
            } else {
                GM_notification({
                    title: `《${GM_info.script.name}》脚本提示`,
                    text: "WPS任务中心签到失败"
                });
            }
            GM_log(`${GM_info.script.name}脚本日志：脚本执行成功`, "info");
            resolve("脚本执行成功");
        } catch (error) {
            GM_log(`${GM_info.script.name}脚本日志：${error.toString()}`, "error");
            GM_notification({
                title: `《${GM_info.script.name}》脚本提示`,
                text: `《${GM_info.script.name}》脚本错误日志：${error.toString()}`
            });
            reject("脚本执行失败");
        }
    }

    asyncFunction().then(r => resolve(r)).catch(e => reject(e));
});